package io.gitee.zicai.graphql.sample.self.fetcher;

import graphql.schema.DataFetcher;
import io.gitee.zicai.graphql.sample.dao.StudentRepo;
import io.gitee.zicai.graphql.sample.entity.QStudent;
import io.gitee.zicai.graphql.sample.entity.Student;
import io.gitee.zicai.graphql.sample.self.GraphQLBaseDataFetcher;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * StudentDataFetcher
 *
 * @author zicai
 * @since 2021-03-09
 */
@Component
public class StudentDataFetcher extends GraphQLBaseDataFetcher<StudentRepo, Student, String> {

    public DataFetcher<List<Student>> queryByName() {
        return env -> {
            String name = env.getArgument("name");
            return this.findAll(QStudent.student.name.like("%" + name + "%"));
        };
    }

    public DataFetcher<Student> updateById() {
        return env -> {
            String id = env.getArgument("id");
            String name = env.getArgument("name");
            Integer age = env.getArgument("age");

            return dao.findById(id)
                    .map(o -> o.setName(name).setAge(age))
                    .map(dao::saveAndFlush)
                    .orElse(null);
        };
    }

    public DataFetcher<Student> save() {
        return env -> {
            String name = env.getArgument("name");
            Integer age = env.getArgument("age");

            Student student = new Student().setName(name).setAge(age);
            return dao.saveAndFlush(student);
        };
    }

}
